$(document).ready(function () {
    $('#cards').hide();
    initCards();
    initTable();
    initDepts();
    initDeptsForSearch();
    $('#btnAdd').bind('click', btnAddClick);
    $('#btnEdit').bind('click', btnEditClick);
    $('#btnRemove').bind('click', btnRemoveClick);
    $('#btnSave').bind('click', btnSaveClick);

    $('#btnSearch').bind('click', btnSearchClick);
    /*$('#toggleView li').each(function () {
         $(this).bind('click',function () {
             $('#toggleView .active').removeClass('active');
             $(this).addClass('active');
           if( $('#cards').attr('display') =='none')  {
                 $('#lists').slideUp(1000,function () {
                     $('#cards').slideDown(2000)
                 })
           }
         })
    })*/
    $('#showTable').bind('click', function () {
        $('.active').removeClass('active');
        $(this).addClass('active');
        $('#cards').slideUp(1000, function () {
            $('#lists').slideDown(2000);
        })
    })
    $('#showCards').bind('click', function () {
        $('.active').removeClass('active');
        $(this).addClass('active');
        /*卡片效果*/
        $('#lists').slideUp(1000, function () {
            $('#cards').slideDown(2000);
        });
    });
})

function initCards() {
    var row;
    $.ajax({
        url: 'http://test.org/employees',
        method: 'get',
        dataType: 'json',
        success: function (data) {
            $.each(data, function (index, item) {
                if (index % 3 == 0) {
                    row = $('<div></div>').addClass('row');
                    $('#cards').append(row);
                }
                var panel = $('<div></div>')
                    .addClass('panel')
                    .addClass('panel-success')
                    .addClass('col-md-3')
                    .addClass('col-md-offset-1')
                    .addClass('padding-0');
                var headding = $('<div></div>').addClass("panel-heading");
                var title = $('<h3></h3>').text(item.empName);
                headding.append(title);
                var panelBody = $('<div></div>').addClass("panel-body");
                var avatar = $('<img class="img-circle" />').attr('src', item.img);
                panelBody.append(avatar);
                var footer = $('<div></div>').addClass("panel-footer");
                panel.append(headding).append(panelBody).append(footer);
                row.append(panel);
            })
        }
    })
}

function initTable() {
    $.ajax({
        url: 'http://test.org/employees',
        method: 'get',
        dataType: 'json',
        success: function (data) {
            localStorage.setItem("emps", JSON.stringify(data));
            $('#list').bootstrapTable({
                data: data,
                columns: columns,
                pagination: true,
                toolbar: '#toolbar',
                pageSize: 5,
                showExport: true,
                showColumns: true,
                exportDataType: 'basic',
                singleSelect: true,
                clickToSelect: true
            })
        }
    })
}

function freshTable() {
    var data = window.localStorage.getItem("emps");
    data = JSON.parse(data);
    $('#list').bootstrapTable('destroy');
    $('#list').bootstrapTable({
        data: data,
        columns: columns,
        pagination: true,
        toolbar: '#toolbar',
        pageSize: 5,
        showExport: true,
        showColumns: true,
        exportDataType: 'basic'
    })
}

var columns = [
    {
        checkbox: true
    },
    {
        field: "empName",
        title: "员工姓名"
    }, {
        field: "gender",
        title: "性别",
        formatter: function (val, row, index) {
            if (val == "male") {
                return "男";
            } else {
                return "女";
            }
        }
    }, {
        field: "age",
        title: "年龄"
    }, {
        field: "dept.name",
        title: "部门"
    },
    {
        field: "title.name",
        title: "职务"
    },
    {
        field: "id",
        title: "操作",
        width: '180px',
        formatter: function () {
            var box = $("<div></div>"); //用于存放html
            var btnEdit = $('<button></button>')
                .text("修改")
                .addClass("btn")
                .addClass("btn-warning");
            var btnRemove = $('<button></button>')
                .text("删除")
                .addClass("btn")
                .addClass("btn-danger");
            box.append(btnEdit);
            box.append(btnRemove);
            return box.html();
        }
    }
]

function btnAddClick() {
    $('#infoTitle').text("添加员工");
    $('#info').modal()
}

function btnSaveClick() {
    $.ajax({
        url: "http://test.org/employee/save",
        method: "get",
        dataType: "json",
        success: function (data) {
            /**
             * 向本地保存数据
             * 用来模拟数据库的数据存储功能
             * */
            var emps = localStorage.getItem("emps");
            emps = JSON.parse(emps);
            if ($('#empId').val() == '') {
                emps.unshift(
                    {
                        "empName": $('#empName').val(),
                        "gender": $('[name="gender"]:checked').val(),
                        "dept": {
                            dict_id: $('#dept').val(),
                            name: $('#dept :selected').val()
                        }
                    }
                )
            } else {
                var current = emps.find(function (emp) {
                    return emp.id == parseInt($('#empId').val())
                })
                current.empName = $('#empName').val();
                current.age = $('#age').val();
                emps.splice(current.id - 1, 1, current);
            }
            window.localStorage.setItem("emps", JSON.stringify(emps));
            $('#saveMsg').fadeIn(3000, function () {
                freshTable();
                $('#info').modal('hide');
            })
        }
    })
}

function btnEditClick() {
    $('#infoTitle').text("修改员工");

    var row = $('#list').bootstrapTable('getSelections')[0];


    $('#empId').val(row.id);

    $('#empName').val(row.empName);
    $('#age').val(row.age);

    if (row.gender == 'male') {
        $('#male').attr("checked", "checked");
    } else {
        $('#female').attr("checked", "checked");
    }

    $('#dept').val(15)


    $('#info').modal();
}

function initDepts() {
    $.ajax({
        url: '../../mock/depts.json',
        methods: 'get',
        dataType: 'json',
        success: function (data) {
            $.each(data, function (index, item) {
                var opt = $('<option></option>').val(item.dict_id).text(item.name);
                $('#dept').append(opt);

            })
        }
    })
}


function initDeptsForSearch() {
    $.ajax({
        url: '../../mock/depts.json',
        methods: 'get',
        dataType: 'json',
        success: function (data) {
            var fullOpt = $('<option></option>').val(0).text("----所有部门----");
            $('#deptForSearch').append(fullOpt);
            $.each(data, function (index, item) {
                var opt = $('<option></option>').val(item.dict_id).text(item.name);
                $('#deptForSearch').append(opt);

            })
        }
    })
}

function btnRemoveClick() {

    if (confirm("是否需要删除本条数据？")) {
        var row = $('#list').bootstrapTable('getSelections')[0];

        var emps = localStorage.getItem("emps");
        emps = JSON.parse(emps);

        var current = emps.find(function (emp) {
            return emp.id == row.id;
        })

        emps.splice(current.id - 1, 1);// 删除

        window.localStorage.setItem("emps", JSON.stringify(emps));

        freshTable();

        // emps.splice(current.id-1,1,current);// 修改
    }
}

function btnSearchClick() {
    var query = {};

    query.empName = $('#nameForSearch').val().trim();
    query.age={
        begin:parseInt($('#begin').val()) ,
        end:parseInt($('#end').val())
    }

    var emps = localStorage.getItem("emps");
    emps = JSON.parse(emps);

    emps = emps.filter(function (emp) {
        return emp.empName.indexOf(query.empName)>0
            && emp.age<=query.age.end
            && emp.age>=query.age.begin;
    })

    window.localStorage.setItem("emps", JSON.stringify(emps));

    freshTable();
}